/*******************************************************************************
 * ***** BEGIN LICENSE BLOCK This file is part of StalkerFox. StalkerFox is free
 * software: you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * 
 * StalkerFox is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * StalkerFox. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE
 * BLOCK *****
 */

// StalkerFox by Martin Obiols Herrera <olemoudi@gmail.com>

// Constants

// Data source types

// defines a sequence of events like: offline, online, busy, online, offline,
// away...
// it only matters when the event switches from previous state to another one.
const DATATYPE_PRESENCE = 0; 
// defines a sequence of different events. It matters the time of the last
// event.
const DATATYPE_ACTIONLIST = 1; // defines a sequence of diferent events

//Event types


function DataSource(type, sourceid, sourceurl, xbase, xcontent, xtime) {
	this.init(type, sourceid, sourceurl, xbase, xcontent, xtime);
}

DataSource.prototype = {
	init : function(type, sourceid, sourceurl, xbase, xcontent, xtime) {
		this._type = type;
		this._sourceid = sourceid;
		this._sourceurl = sourceurl;
		this._xbase = xbase;
		this._xcontent = xcontent;
		this._xtime = xtime;
		this._createBrowser();
	},
	activate : function() {
		this._active = true;
	},
	deactivate : function() {
		this._active = false;
	},
	isActive : function() {
		return _active;
	},
	update : function() {
	},
	getEvents : function() {
	},
	getSourceId : function() {
		return this._sourceid;
	},
	getSourceURL : function() {
		return this._sourceurl;
	},
	// private class atributes
	_createBrowser : function() {
		var vbox = document.createElement('vbox');
		vbox.setAttribute('hidden', 'false');
		vbox.setAttribute('id', 'test');
		vbox.setAttribute('height', '0');
		vbox.setAttribute('width', '0');
		var hiddenbrowser = document.createElement("browser");		
		hiddenbrowser.setAttribute('type','content');
		hiddenbrowser.setAttribute('src','');
		//i.setAttribute('name',sourceid);
		hiddenbrowser.setAttribute('id',this.getSourceId());
		hiddenbrowser.setAttribute('hidden','false');
		hiddenbrowser.setAttribute('height','0');
		var browser = document.getElementById('browser');
		browser.appendChild(vbox);
		vbox.appendChild(hiddenbrowser);
		this.browser = hiddenbrowser;
	},
	_active : false,
	_updateinterval : null,
	_sourceid : "", // targetid@sourcename
	_type : DATATYPE_PRESENCE,
	_sourceurl : "",
	_xbase : "",
	_xcontent : "",
	_xtime : "",
	browser : null
	}

function Event(datasource, msg) {
	this.init(datasource, msg);
}

Event.prototype = {
	init : function(datasource, msg) {
		this._datasource = datasource;
		this._msg = msg;
	},
	getMsg : function() {
		return this._msg;
	},
	getDataSource : function() {
		return this._datasource;
	},
	// private attributes
	_datasource : null,
	_msg : ""
}

/*
// Now it is time to create the timer...  
var timer 
  = Components.classes["@mozilla.org/timer;1"]
      .createInstance(Components.interfaces.nsITimer);
      
       timer.initWithCallback(
   event,
   10000,
   Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);

*/


function DSUpdateTask(datasource, stalktask) {
	this.init(datasource, stalktask);
}
//var main = Components.classes["@mozilla.org/thread-manager;1"].getService().mainThread;

DSUpdateTask.prototype = {
		init : function(datasource, stalktask) {
			this._datasource = datasource;
			this._stalktask = stalktask;
		},
		notify : function(timer) {
			try {
				// update magic stuff
				//alert(Components.classes["@mozilla.org/thread-manager;1"].getService().isMainThread);
				//var main = Components.classes["@mozilla.org/thread-manager;1"].getService().mainThread;
				//main.dispatch(new DSRetrieveRawData(this._datasource, this), main.DISPATCH_NORMAL);				
				//var ds = new DSRetrieveRawData(this._datasource, this);
				//ds.run();			
				//this._stalktask.receiveEvents(events);
				//var tm = Components.classes["@mozilla.org/thread-manager;1"]
				                            //.getService(Components.interfaces.nsIThreadManager);
				//tm.mainThread.dispatch(new DSRetrieveRawData(this._datasource, this), Components.interfaces.nsIThread.DISPATCH_NORMAL);

				this._datasource.browser.webNavigation.allowAuth = true;
				this._datasource.browser.webNavigation.allowImages = false;
				this._datasource.browser.webNavigation.allowJavascript = true;
				this._datasource.browser.webNavigation.allowMetaRedirects = true;
				this._datasource.browser.webNavigation.allowPlugins = false;
				this._datasource.browser.webNavigation.allowSubframes = false;
				this._datasource.browser.addEventListener("DOMContentLoaded", this.onData, true);			
				this._datasource.browser.webNavigation.loadURI(this._datasource.getSourceURL(),Components.interfaces.nsIWebNavigation,null,null,null);
								
			} catch (err) {
				Components.utils.reportError(err);
			}
		    // When it's done, call back to the main thread to let it know
		    // we're finished.			
		    //main.dispatch(new mainThread(this.threadID, this.result), background.DISPATCH_NORMAL);
		},
		// we enter here on main thread <--- NOOOO
		onData : function(pagedata) {
			// process rawdata
			// send events
			//alert('ondata!');
			var doc = pagedata.originalTarget;
			var url = doc.location.href;
			if (pagedata.originalTarget.nodeName == "#document") { // ok, it's a real page, let's do our magic
				dump("[DF] URL = "+url+"\n");
				var result = doc.evaluate("/html/body/center/table/tbody/tr/td/table[5]/tbody/tr[2]/td[2]/text()[3]",doc,null,XPathResult.ANY_TYPE,null);
				alert("[MediaVida] OleMoudi is now " +result.iterateNext().textContent);
				//dump("[DF] TEXT in /html/head/title = "+text+"\n");
				///html/body/center/table/tbody/tr/td/table[5]/tbody/tr[2]/td[2]
			}
			
			
			/*var main = Components.classes["@mozilla.org/thread-manager;1"].getService().mainThread;
			main.dispatch(new DSEventDispatcher(this._events, stalktask),
			        main.DISPATCH_NORMAL);*/			
		},
		_datasource : null,
		_stalktask : null
}

var ds = new DataSource(DATATYPE_PRESENCE, 'ole@mv', 'http://www.mediavida.com/perfil.php?id=1341', '','','');
var updatetask = new DSUpdateTask(ds,null);
var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
//timer.initWithCallback(updatetask, 10000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);



/*
function DSRetrieveRawData(datasource, DSUpdateTask) {
	this.init(datasource, DSUpdateTask);
}

DSRetrieveRawData.prototype = {
	init : function(datasource, DSUpdateTask) {
		this._datasource = datasource;
		this._DSUpdateTask = DSUpdateTask;		
	},
	run : function() {	
		try {
			/*var aBox = document.getElementById("aBox");

			 * var button = document.createElement("button");
			  button.setAttribute("label","A Button");
			  aBox.appendChild(button); */			
			//var iframe = document.getElementById(this._datasource.getSourceId());
			//var iframe = this._datasource.iframe;
			//alert(document.nodeName);
			//alert(document.id);
			//alert(this._datasource.getSourceId());
			//alert(1);
			/*var browser = document.getElementById('browser');
			//alert(browser.nodeName)
			var vbox = document.createElement('vbox');
			vbox.setAttribute('hidden', 'false');
			vbox.setAttribute('id', 'test');
			vbox.setAttribute('height', '500');
			vbox.setAttribute('width', '500');
			var iframe = document.createElement("browser");		
			iframe.setAttribute('type','content');
			iframe.setAttribute('src','');
			//i.setAttribute('name',sourceid);
			iframe.setAttribute('id',this._datasource.getSourceId());
			iframe.setAttribute('hidden','false');
			iframe.setAttribute('height','400');
			browser.appendChild(vbox);
			vbox.appendChild(iframe);				
			//alert(1);
			iframe.style.height = "100px";
			iframe.webNavigation.allowAuth = true;
			iframe.webNavigation.allowImages = false;
			iframe.webNavigation.allowJavascript = true;
			iframe.webNavigation.allowMetaRedirects = true;
			iframe.webNavigation.allowPlugins = false;
			iframe.webNavigation.allowSubframes = false;
			iframe.addEventListener("DOMContentLoaded", this._DSUpdateTask.onData, true);			
			iframe.webNavigation.loadURI(this._datasource.getSourceURL(),Components.interfaces.nsIWebNavigation,null,null,null);
			//this._stalktask.receiveEvents(events);
		} catch (err) {
			Components.utils.reportError(err);
		}
	},
	QueryInterface: function(iid) {
		if (iid.equals(Components.interfaces.nsIRunnable) ||
				iid.equals(Components.interfaces.nsISupports)) {
			return this;
	    }
	    throw Components.results.NS_ERROR_NO_INTERFACE;
	},
	// private attributes
	_datasource : null,
	_DSUpdateTask : null
}


var ds = new DataSource(DATATYPE_PRESENCE, 'ole@mv', 'http://www.mediavida.com/perfil.php?id=1341', '','','');

var updatetask = new DSUpdateTask(ds,null);
updatetask.notify(null);


/*

DSEventDispatchTask(events, stalktask) {
	this.init(events, stalktask);
}

DSEventDispatchTask.prototype = {
	init : function(events, stalktask) {
		this._events = event;
		this._stalktask = stalktask;
	},
	run : function() {
		try {
			this._stalktask.receiveEvents(events);
		} catch (err) {
			Components.utils.reportError(err);
		}
	},
	QueryInterface: function(iid) {
		if (iid.equals(Components.interfaces.nsIRunnable) ||
				iid.equals(Components.interfaces.nsISupports)) {
			return this;
	    }
	    throw Components.results.NS_ERROR_NO_INTERFACE;
	},
	// private attributes
	_events : null,
	_stalktask : null
}
*/